<?php

require('init.php');

// set channel timezone
date_default_timezone_set("America/New_York");

$counter = rand(1, 10);
$start=microtime(true);
while ($start+MAX_EXECUTION_TIME>microtime(true)) {
	// Every second, sent a "ping" event.
	updateTime();

	// Send a simple message at random intervals.
	$counter--;

	//if (!$counter) {
		echo 'data: This is a message at time ' . date(DATE_ISO8601, $curDate).PHP_EOL.PHP_EOL;
		$counter = rand(1, 10000);
		
		pushTimeline(
			3434,	// timeline id
			25,		// duration 
			array(
				array(
					'screenid'=>1,
					'transition'=>'fadein',
					'transitionDuration'=>3,
					'template'=>generateScreen(
						'image_fullscreen.tpl',
						# common variables 
						array(
							'bgcolor'=>'#245555',
							//'bgimage'=>'http://localhost/digital/images/aishwaryaraiface.jpg',
						), 
						array('image'=>'http://localhost/digital/images/aishwaryaraiface.jpg')
					),
					'duration'=>10,
				),
				array(
						'screenid'=>2,
						'transition'=>'fadein',
						'transitionDuration'=>3,
						'template'=>generateScreen(
								'image_fullscreen.tpl',
								# common variables
								array(
										'bgcolor'=>'#245555',
										//'bgimage'=>'http://localhost/digital/images/night-on-east-river-ny.jpg',
								),
								array('image'=>'http://localhost/digital/images/night-on-east-river-ny.jpg')
						),
						'duration'=>10,
				),

			)
		);
	//}

	ob_flush();
	flush();
	
	
	// sleep till next second
	while(1) usleep(msToNextSecond());
}

function msToNextSecond() {
	$time=microtime(true);
	return round(($time-((int)$time))*1000)+1;
}

function pushTimeline($timeline, $duration, $args) {
	$data=array(
		'timeline'=>$timeline,
		'args'=>$args,
		'duration'=>$duration,
	);
	
	echo "event: timeline".PHP_EOL;
	echo 'data: '.json_encode($data).PHP_EOL.PHP_EOL;
}

/*
 * Method to update time at screen timezone
 */
function updateTime() {
	$curDate = time();
	
	// update current time every 5s
	if($GLOBALS['curDate']!=$curDate && ($curDate%5==0)){
		echo "event: ping".PHP_EOL;
		echo 'data: {"time": "' . date(DATE_ISO8601, $curDate) . '"}'.PHP_EOL.PHP_EOL;
		$GLOBALS['curDate']=$curDate;
	}
}
?>